/* ============================================================================ */
/*                         IMPORT AND INITIAL SETUP                             */
/* ============================================================================ */

clear all

/* Import the shift-share dataset */
import delimited "$input\shift_share_data_set.csv", clear

/* Convert dates to Stata formats */
gen time = date(date, "YMD")
gen qdate = qofd(time)
format time %td
format qdate %tq

/* Convert loan start date */
gen startoutsideloan = date(datestart, "YMD")
gen qstartoutsideloan = qofd(startoutsideloan)
format startoutsideloan %td
format qstartoutsideloan %tq

/* Sort dataset by firm and quarter */
sort siren qdate

/* Define post-loan period indicators */
gen p2pqtrcapturing = qdate >= qstartoutsideloan if p2p == 1
gen outsideloanqtrcapturing = qdate >= qstartoutsideloan if p2p == 0
gen p2pqtrcapturingstrict = qdate > qstartoutsideloan if p2p == 1
gen outsideloanqtrcapturings = qdate > qstartoutsideloan if p2p == 0

/* Compute time difference in quarters */
gen deltaquarter = qdate - qstartoutsideloan
su deltaquarter, d

/* Create dummy variable for [-4, 8] quarters around event */
gen deltaqdummy = deltaquarter >= -4 & deltaquarter <= 8
replace deltaqdummy = . if deltaquarter == .

/* ============================================================================ */
/*                     INDUSTRY CLASSIFICATIONS & CLEANING                      */
/* ============================================================================ */

/* Pool P, Q, R, S together as public sector */
replace industry = "public" if inlist(industry, "P", "Q", "R", "S")

/* Merge certain industry categories */
replace industry = "DE" if inlist(industry, "D", "E")
replace industry = "FL" if inlist(industry, "F", "L")

/* Remove industries not relevant for analysis */
drop if inlist(industry, "A", "K", "O", "B", "DE", "0000Z")

/* Encode industry variable */
egen industry10 = group(industry)

/* Standardize rating categories */
replace rating = "3A" if rating == "3++"
replace rating = "3B" if rating == "3+"
replace rating = "3C" if rating == "3"
replace rating = "4A" if rating == "4+"
replace rating = "4B" if rating == "4"
replace rating = "5A" if rating == "5+"
replace rating = "5B" if rating == "5"

encode rating, gen(ratinge)
replace ratinge = ratinge - 1
replace ratinge = 13 if ratinge == 0
tab rating ratinge, nolab

/* Define panel structure */
tsset siren qdate, quarterly

/* Keep data only within the specified time window */
keep if qdate < qofd(date("20200101", "YMD"))
keep if qdate > qofd(date("20131231", "YMD"))

/* Save dataset for later merging */
tempfile dataset1
save `dataset1'

/* ============================================================================ */
/*                     IMPORT MAIN DATASET (BEFORE PSM)                         */
/* ============================================================================ */

use "$output\ifp_scrapped_aggregated_industries_modified.dta", clear

/* Keep only quarter-end observations */
keep if inlist(datemonth, 3, 6, 9, 12)
format mdate %tm
gen qdate = qofd(dofm(mdate))
format qdate %tq

/* Generate key financial variables */
gen lloan = log(ltloan + bm + bi)
gen lother = log(stloan + oc)
gen lloanfilled = lloan

sort siren qdate

/* Keep only firms in t-test sample */
merge m:1 siren using "$output\ifp_ttest_siren_list.dta", keepusing(siren)
keep if _merge == 3
drop _merge

/* Generate credit line dummy */
preserve
keep if delta < 0
collapse (sum) co, by(siren)
gen codummy = co > 0
drop co
save "$output\data_co_dummy.dta", replace
restore

/* Encode firm ratings */
egen ratingint = group(rating)
replace ratingint = ratingint - 1
replace ratingint = 13 if ratingint == 0

/* Merge credit line dummy */
merge m:1 siren using "$output\data_co_dummy.dta"

/* Label variables */
label var r1filled "Working capital"
label var r3filled "EBIT"
label var r5filled "Sales"
label var r12filled "Investment"
label var r13filled "Debt"
label var logassets_filled "Total Assets"
label var logemployees "Employment"
label var r_collateral_filled "Tangible assets"
label var rdcostsfilled "R&D costs filled"
label var ratingint "Rating"
label var codummy "$\mathbbm{1}$(Credit\ line)"

/* Define control variables */
global control `"r1filled r3filled r5filled r12filled r13filled logassets_filled logemployees r_collateral_filled ratingint"'

/* Keep relevant variables */
keep qdate siren lloan* lother $control

/* Merge with first dataset */
merge 1:1 siren qdate using `dataset1', nogen

/* Filter dates >= 2014q1 (shift-share dataset does not cover earlier) */
keep if qdate >= tq(2014q1)

/* ============================================================================ */
/*                          FIXED EFFECTS VARIABLES                             */
/* ============================================================================ */

egen ind_qtr = group(industry10 qdate)
egen size_qtr = group(size qdate)
egen reg_qtr = group(region qdate)
egen rat_qtr = group(ratinge qdate)

replace outsideloanqtrcapturing = 0 if outsideloanqtrcapturing == .
replace p2pqtrcapturing = 0 if p2pqtrcapturing == .
gen post = p2pqtrcapturing + outsideloanqtrcapturing

replace outsideloanqtrcapturings = 0 if outsideloanqtrcapturings == .
replace p2pqtrcapturingstrict = 0 if p2pqtrcapturingstrict == .
gen poststrict = p2pqtrcapturingstrict + outsideloanqtrcapturings

/* ============================================================================ */
/*                                LOGGING                                       */
/* ============================================================================ */

capture log close
log using "$logs\shift_share_placebo.log", replace

/* ============================================================================ */
/*                         GENERATE CONTROL VARIABLES                           */
/* ============================================================================ */

foreach var in $control {
    gen `var'_0 = `var' /* Create a duplicate variable */
    replace `var'_0 = 0 if `var' == . /* Replace missing values with 0 */
    gen dum_`var' = (`var' == .) /* Generate dummy for missing values */
}

/* Define adjusted control variables */
global control_0 `"*_0 dum_*"'
	
/* ============================================================================ */
/*                           PLACEBO TEST TABLE                                 */
/* ============================================================================ */

foreach j in 2 3 4 5 { 

    /* ------------------------------------------------------------------------
       Reset variables before defining new ones for each iteration 
       ------------------------------------------------------------------------ */
    capture drop scoredelta* volloan*

    /* Generate placebo secured loan variables */
    gen scoredeltap2p = secured`j'2
    xtset siren qdate

    /* Keep the score delta value fixed at the quarter when the P2P loan was granted */
    replace scoredeltap2p = . if p2pqtrcapturing == 0
    replace scoredeltap2p = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward scoredeltap2p, replace
    by siren: replace scoredeltap2p = scoredeltap2p[_N]

    /* Generate secured loan for control group */
    gen scoredeltacontran = secured`j'2
    replace scoredeltacontran = . if outsideloanqtrcapturing == 0
    replace scoredeltacontran = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward scoredeltacontran, replace
    by siren: replace scoredeltacontran = scoredeltacontran[_N]

    /* Merge P2P and control secured loan scores */
    gen scoredeltaboth = scoredeltacontran if p2p == 0
    replace scoredeltaboth = scoredeltap2p if p2p == 1
    gen scoredeltapost = scoredeltaboth * post

    /* ------------------------------------------------------------------------
       Generate volume loan variables (Shift-share control of credit supply)
       ------------------------------------------------------------------------ */
    gen volloanp2pv = logloan`j'2
    replace volloanp2pv = . if p2pqtrcapturing == 0
    replace volloanp2pv = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward volloanp2pv, replace
    by siren: replace volloanp2pv = volloanp2pv[_N]

    /* Generate control group volume loan */
    gen volloancontranv = logloan02
    replace volloancontranv = . if outsideloanqtrcapturing == 0
    replace volloancontranv = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward volloancontranv, replace
    by siren: replace volloancontranv = volloancontranv[_N]

    /* Merge P2P and control group volume loan scores */
    gen volloanbothv = volloancontranv if p2p == 0
    replace volloanbothv = volloanp2pv if p2p == 1
    gen volloanv = volloanbothv * post

    /* ------------------------------------------------------------------------
       Display iteration number
       ------------------------------------------------------------------------ */
    di "************************* `j' ********************", in red

    /* ===================================================================== */
    /*                             FIRST STAGE                               */
    /* ===================================================================== */
    
    eststo fs`j': reghdfe p2pqtrcapturing scoredeltapost post volloanv $control_0 if deltaqdummy, ///
                   cl(siren) a(i.qdate i.siren)

    /* Count firms in each treatment group */
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    /* Add results to estimation table */
    estadd local qdate     "Y", replace
    estadd local siren     "Y", replace
    estadd local control   "Y", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace

    /* ===================================================================== */
    /*                         SECOND STAGE (IV)                            */
    /* ===================================================================== */

    eststo col`j': ivreghdfe lloan (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
                    if deltaqdummy, cl(siren) a(i.qdate i.siren)

    /* Count firms in each treatment group again */
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    /* Add results to estimation table */
    estadd local qdate     "Y", replace
    estadd local siren     "Y", replace
    estadd local control   "Y", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace
    estadd scalar f2 = e(widstat)

} /* End of loop */

	
/* ============================================================================ */
/*                           PLACEBO TEST TABLE                                 */
/* ============================================================================ */

foreach j in 0 { 

    /* ------------------------------------------------------------------------
       Reset variables before defining new ones for each iteration 
       ------------------------------------------------------------------------ */
    capture drop scoredelta* volloan*

    /* Generate placebo secured loan variables */
    gen scoredeltap2p = secured`j'2
    xtset siren qdate

    /* Keep the score delta value fixed at the quarter when the P2P loan was granted */
    replace scoredeltap2p = . if p2pqtrcapturing == 0
    replace scoredeltap2p = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward scoredeltap2p, replace
    by siren: replace scoredeltap2p = scoredeltap2p[_N]

    /* Generate secured loan for control group */
    gen scoredeltacontran = secured`j'2
    replace scoredeltacontran = . if outsideloanqtrcapturing == 0
    replace scoredeltacontran = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward scoredeltacontran, replace
    by siren: replace scoredeltacontran = scoredeltacontran[_N]

    /* Merge P2P and control secured loan scores */
    gen scoredeltaboth = scoredeltacontran if p2p == 0
    replace scoredeltaboth = scoredeltap2p if p2p == 1
    gen scoredeltapost = scoredeltaboth * post

    /* ------------------------------------------------------------------------
       Generate volume loan variables (Shift-share control of credit supply)
       ------------------------------------------------------------------------ */
    gen volloanp2pv = logloan`j'2
    replace volloanp2pv = . if p2pqtrcapturing == 0
    replace volloanp2pv = . if !(L.p2pqtrcapturing == 0 & p2pqtrcapturing == 1)
    by siren: carryforward volloanp2pv, replace
    by siren: replace volloanp2pv = volloanp2pv[_N]

    /* Generate control group volume loan */
    gen volloancontranv = logloan02
    replace volloancontranv = . if outsideloanqtrcapturing == 0
    replace volloancontranv = . if !(L.outsideloanqtrcapturing == 0 & outsideloanqtrcapturing == 1)
    by siren: carryforward volloancontranv, replace
    by siren: replace volloancontranv = volloancontranv[_N]

    /* Merge P2P and control group volume loan scores */
    gen volloanbothv = volloancontranv if p2p == 0
    replace volloanbothv = volloanp2pv if p2p == 1
    gen volloanv = volloanbothv * post

    /* ------------------------------------------------------------------------
       Display iteration number
       ------------------------------------------------------------------------ */
    di "************************* `j' ********************", in red

    /* ===================================================================== */
    /*                         SECOND STAGE (IV)                            */
    /* ===================================================================== */

    eststo col`j': ivreghdfe lother (p2pqtrcapturing = scoredeltapost) post volloanv $control_0 ///
                    if deltaqdummy, cl(siren) a(i.qdate i.siren)

    /* Count firms in each treatment group */
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    /* Add results to estimation table */
    estadd local qdate     "Y", replace
    estadd local siren     "Y", replace
    estadd local control   "Y", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace
    estadd scalar f2 = e(widstat)

    /* Save sample indicator */
    capture drop sample 
    gen sample = e(sample)

    /* ===================================================================== */
    /*                             FIRST STAGE                               */
    /* ===================================================================== */

    eststo fs`j': reghdfe p2pqtrcapturing scoredeltapost post volloanv $control_0 ///
                   if sample, cl(siren) a(i.qdate i.siren)

    /* Count firms in each treatment group */
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    /* Add results to estimation table */
    estadd local qdate     "Y", replace
    estadd local siren     "Y", replace
    estadd local control   "Y", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace    

    /* ===================================================================== */
    /*                           REDUCED FORM                               */
    /* ===================================================================== */

    eststo rf`j': reghdfe lother scoredeltapost post volloanv $control_0 ///
                   if sample, cl(siren) a(i.qdate i.siren)

    /* Count firms in each treatment group */
    qui levelsof siren if p2p == 1 & e(sample), local(sirens_p2p1)
    qui levelsof siren if p2p == 0 & e(sample), local(sirens_p2p0)
    local num_sirens_p2p1: word count `sirens_p2p1'
    local num_sirens_p2p0: word count `sirens_p2p0'

    /* Add results to estimation table */
    estadd local qdate     "Y", replace
    estadd local siren     "Y", replace
    estadd local control   "Y", replace
    estadd local num_sirens_p2p1 `num_sirens_p2p1', replace
    estadd local num_sirens_p2p0 `num_sirens_p2p0', replace    

}

/* ============================================================================ */
/*                            EXPORT Table 8b                                  */
/* ============================================================================ */

label var scoredeltapost "Secured ratio $\times$ Post"
label var post "Post"
label var p2pqtrcapturing "FinTech $\times$ Post"
label var volloanv "Credit supply  $\times$ Post"

esttab col2 col3 col4 col5 col0 using "$tables\shift-share_placebo.tex", replace ///
       star(* 0.10 ** 0.05 *** 0.01) nomtitles fragment gap booktabs label nonote noobs ///
       eqlabels(,none) b(%9.3f) se(%9.3f) ///
       stats(qdate siren control N f2, labels("Quarter FE" "Firm FE" "Control" ///
       "\midrule Observations" "F-stat") ///
       layout("\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" ///
       "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}") ///
       fmt(%9.0fc %9.0fc %9.0fc %9.0fc %9.3fc)) ///
       keep(p2pqtrcapturing post volloanv) ///
       order(p2pqtrcapturing post volloanv) ///
       mgroups("log(Long-term credit)" "log(Other credit)", pattern (1 0 0 0 1) ///
       prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))

log close
